import axios from 'axios'

import nprogress from 'nprogress'

import 'nprogress/nprogress.css'

import store from "@/store";

// 创建 axios 实例
const requests = axios.create({
    baseURL: '/api',
    timeout: 5000,
})

// 请求拦截器
requests.interceptors.request.use((config) => {
    nprogress.start()
    // 游客模式
    if (store.state.shopcart.USER_ID) {
        config.headers.userTempId = store.state.shopcart.USER_ID;
    }

    // 登录模式
    if (store.state.user.token) {
        config.headers.token = store.state.user.token;
    }
    return config
})

// 响应拦截器
requests.interceptors.response.use((res) => {
    nprogress.done()
    return res.data
}, (error) => {
    return Promise.reject(error.response)
})

export default requests